package org.mspring.mlog.service;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.mspring.mlog.dao.AttachmentDao;
import org.mspring.mlog.entity.Attachment;
import org.mspring.platform.qiniu.QiniuStorageService;
import org.mspring.platform.security.SecurityUtils;
import org.mspring.platform.security.entity.User;
import org.mspring.platform.security.exception.UNLoginException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qiniu.api.io.PutRet;

/**
 *
 * @author Gao Youbo
 * @since 2013-06-18 16:34:42
 */
@Service
@Transactional
public class AttachmentService {

    public static final String ATTACH_KEY_PRE = "attach-";

    @Autowired
    private QiniuStorageService storageService;
    @Autowired
    private AttachmentDao attachmentDao;

    public Attachment get(long id) {
        return attachmentDao.get(id);
    }

    /**
     * 根据附件来源编号查找该附件来源对应的附件
     *
     * @param foreignType
     *            类型
     * @param foreignKey
     *            编号
     * @return
     */
    public List<Attachment> listAttachmentsByForeign(String foreignType, long foreignKey) {
        return attachmentDao.listByForeign(foreignType, foreignKey);
    }

    public long create(InputStream stream, String foreignType, Long foreignKey) throws Exception {
        byte[] bytes = IOUtils.toByteArray(stream);
        return insert(bytes, foreignType, foreignKey);
    }

    public long create(Attachment attachment) throws Exception {
        return attachmentDao.insert(attachment);
    }

    public long insert(byte[] bytes, String foreignType, Long foreignKey) throws Exception {
        User user = SecurityUtils.getCurrentUser();
        if (user == null) {
            throw new UNLoginException();
        }
        String key = ATTACH_KEY_PRE + DigestUtils.md5Hex(bytes);
        PutRet ret = storageService.put(key, bytes);
        if (!ret.ok()) {
            throw new Exception("上传附件失败");
        }
        String url = storageService.getUrl(ret);
        Attachment attachment = new Attachment();
        attachment.setUrl(url);
        attachment.setSize(Long.valueOf(bytes.length));
        attachment.setUser(user.getId());
        attachment.setForeignType(foreignType);
        attachment.setForeignKey(foreignKey);
        attachment.setCreateTime(new Date());
        return attachmentDao.insert(attachment);
    }

    public void delete(long id) {
        Attachment attach = get(id);
        if (attach == null) {
            return;
        }
        attachmentDao.delete(attach);
        storageService.deleteByUrl(attach.getUrl());
    }

    public void delete(String foreignType, long foreignKey) {
        // attachmentDao.deleteByForeign(foreignType, foreignKey);
        List<Attachment> attachments = listAttachmentsByForeign(foreignType, foreignKey);
        if (attachments == null || attachments.isEmpty()) {
            return;
        }
        for (Attachment attachment : attachments) {
            attachmentDao.delete(attachment);
            storageService.deleteByUrl(attachment.getUrl());
        }
    }

    public void update(Attachment attachment) {
        attachmentDao.update(attachment);
    }

    public void setForeignKey(Long id, String foreignType, Long foreignKey) {
        Attachment attachment = get(id);
        if (attachment == null) {
            return;
        }
        attachment.setForeignType(foreignType);
        attachment.setForeignKey(foreignKey);
        attachmentDao.update(attachment);
    }

}
